<?php 
if (! defined('BASEPATH')) exit('No direct script access');

class Subjects extends Controller {

  //php 5 constructor
  function __construct() {
    parent::Controller();
    $this->load->model('Subject');
  }
  
  //php 4 constructor
  function Subjects() {
    parent::Controller();
    $this->load->model('Subject');
  }
  
  /**
   * Viene de listsubjects/:any/:any/faculty_id
   *
   * @param string $faculty_id 
   * @return void
   * @author Ian Murray
   */
  function by_faculty($faculty_id) {
    $this->load->model('Faculty');
    
    $faculty = $this->Faculty->get(array(
        'fields' => 'faculties.*, campuses.name as campus_name',
        'where' => array('id_faculty' => $faculty_id),
        'join' => array(
            'campuses' => 'campuses.id_campus = faculties.campus_id'
          )
      ));
    
    if( ! count($faculty) ) {
      $this->layouts->show_404();
    }
    else {
      /* Obtenemos los ramos, activos eso si */
      $subjects = $this->Subject->get(array(
          'fields' => '*',
          'where' => array('faculty_id' => $faculty_id, 'active' => 't'),
          'order' => 'period desc, name asc'
        ));
      
      /* Mostramos */
      $this->layouts->set_title($faculty[0]['campus_name'] . ' | ' . $faculty[0]['name']);
      $this->layouts->view('subjects/by_faculty', array('faculty' => $faculty[0], 'subjects' => $subjects));
    }
  }

  /**
   * Viene de viewsubject/.../.../.../subject_id
   *
   * @param string $subject_id 
   * @return void
   * @author Ian Murray
   */
  function info($subject_id)
  {
    $subject = $this->Subject->get(array(
        'fields' => 'subjects.*, campuses.name as campus_name, faculties.name as faculty_name',
        'where' => array('id_subject' => $subject_id),
        'join' => array(
            'faculties' => 'faculties.id_faculty = subjects.faculty_id',
            'campuses' => 'campuses.id_campus = faculties.campus_id'
          ),
        'limit' => 1
      ));
    
    if( ! count($subject) ) {
      $this->layouts->show_404();
    }
    else {
      $subject = $subject[0];
      
      /* Cargamos Carpetas y noticias */
      $this->load->model('Folder');
      $this->load->model('News');
      $this->load->model('User');
      
      $news = $this->News->get_by_subject_id($subject_id, array(
        'fields' => 'news.*, users.name, users.id_user',
        'join' => array(
          'users' => 'users.id_user = news.user_id'
        ),
        'order' => 'created desc'
      ));
      
      $folders = $this->Folder->get_by_subject_id($subject_id);
      
      $users = $this->User->get_teachers_and_tas($subject_id);
      
      /* Mostramos */
      $this->layouts->set_title($subject['campus_name'] . ' | ' . $subject['faculty_name'] . ' | ' . $subject['name'] . ' (' . $subject['period'] . ')');
      $this->layouts->add_js('js/folders');
      $this->layouts->add_js('js/options');
      $this->layouts->view('subjects/info', array(
        'subject' => $subject,
        'news' => $news,
        'folders' => $folders,
        'users' => $users
      ));
    }
  }
  
  /**
   * Maneja los cambios de opciones via ajax
   *
   * @param string $action 
   * @param string $setting 
   * @return void
   * @author Ian Murray
   */
  function options($subject_id, $action, $setting)
  {
    $this->authentication->require_login();
    
    switch($action) {
      case 'news': $this->__notifications_options($subject_id, 'news', $setting); break;
      case 'files': $this->__notifications_options($subject_id, 'files', $setting); break;
      
      default: break; /* Nada */
    }
  }
  
  /**
   * Funcion interna para cambiar cosas de notificaciones
   *
   * @param string $what 
   * @param string $setting 
   * @return void
   * @author Ian Murray
   */
  function __notifications_options($subject_id, $what, $setting) 
  {
    if($what == 'news') 
    {
      $this->sg->set_options($subject_id, $this->authentication->user['user']['id_user'], array(
        'news_notifications' => ($setting == 'on') ? DBYES : DBNO
      ));
    }
    
    if($what == 'files') 
    {
      $this->sg->set_options($subject_id, $this->authentication->user['user']['id_user'], array(
        'files_notifications' => ($setting == 'on') ? DBYES : DBNO
      ));
    }
  }
  
  /**
   * Permite crear una suscripcion para un mortal (alumno)
   *
   * @param string $subject_id 
   * @return void
   * @author Ian Murray
   */
  function subscribe($subject_id)
  {
    if( ! $this->authentication->logged_in()) {
      echo '!login!';
      return;
    }
    
    /* Veamos que no este suscrito ya */
    /* Y que exista el ramo */
    if( ! $this->sg->is_subscribed($subject_id) && $subject = $this->Subject->get_by_id($subject_id)) {
      /* Se necesita contrasenha para este ramo? */
      if($subject['password'] != '') {
        /* Sip, veamos si la mandaron y si es igual */
        if( ! $password = $this->input->post('password') ) {
          echo '!error!';
          return;
        }
        
        if( $password != $subject['password']) {
          echo '!error!';
          return;
        }
      }
      /* Asociemos */
      $this->load->model('Permission');
      $this->Permission->associate($this->authentication->user['user']['id_user'], $subject_id, ALUM);
      
      /* Listo */
      /* Javascript se encargará de actualizar */
      echo '!ok!';
    }
    else {
      /* Nada, no deberia pasar */
    }
  }
  
  /**
   * Permite eliminar una suscripcion para un mortal (alumno)
   *
   * @param string $subject_id 
   * @return void
   * @author Ian Murray
   */
  function unsubscribe($subject_id)
  {
    $this->authentication->require_login();
    
    /* Veamos que no sea un profesor o un ayudante */
    if( $this->sg->is_teacher($subject['id_subject']) || $this->sg->is_ta($subject['id_subject'])) {
      /* No pueden eliminar sus sucripciones */
      return;
    }
    
    /* Veamos que no haya eliminado la suscripcion ya */
    /* Y que exista el ramo */
    if( $this->sg->is_subscribed($subject_id) && $this->Subject->get_by_id($subject_id)) {
      /* Desasociemos */
      $this->load->model('Permission');
      $this->Permission->deassociate($this->authentication->user['user']['id_user'], $subject_id);
      
      /* Listo */
      /* Javascript se encargará de actualizar */
    }
    else {
      /* Nada, no deberia pasar */
    }
  }
  
  /**
   * Lista los cursos a los que un usuario esta suscrito
   *
   * @return void
   * @author Ian Murray
   */
  function list_own_subjects()
  {
    $this->authentication->require_login();
    
    $subjects = $this->Subject->get(array(
      'fields' => 'subjects.*, us.type, faculties.name as faculty_name, campuses.name as campus_name',
      'join' => array(
        'users_subjects as us' => 'us.subject_id = subjects.id_subject',
        'faculties' => 'faculties.id_faculty = subjects.faculty_id',
        'campuses' => 'campuses.id_campus = faculties.campus_id'
      ),
      'where' => array('us.user_id' => $this->authentication->user['user']['id_user']),
      'order' => 'subjects.period desc, subjects.name asc'
    ));
    
    $this->layouts->set_title('Mis Cursos');
    $this->layouts->view('subjects/list_own_subjects', array('subjects' => $subjects));
  }
  
  /**
   * Busqueda de ramos
   *
   * @return void
   * @author Ian Murray
   */
  function search()
  {
    echo $this->input->get('query');
  }
}